<template>
  <Page title="听后回答">
    <template #navBarCustom>
      <div class="nav-bar-btns flex">
        <div class="item flex items-center" @click="goToNextQuestion">
          <span class="name text-white">下一题</span>
        </div>
      </div>
    </template>
    <template #content>
      <div class="w-full h-full p-20px box-border">
        <div
          class="container w-full h-full p-20px box-border overflow-hidden bg-white flex flex-col"
        >
          <div class="w-full h-full overflow-scroll">
            <!-- 概况 -->
            <div class="overview text-center">
              <div class="text-333 font-normal">
                <span>总得分：</span>
                <span
                  class="font-semibold"
                  :class="`text-${getScoreClass(score / totalScore)}`"
                  style="font-size: 0.5rem; line-height: 0.7rem"
                  >{{ score }}</span
                >
                <span :class="`text-${getScoreClass(score / totalScore)}`">分</span>
                <span>/{{ totalScore }}分</span>
              </div>
            </div>
            <!-- 详情 -->
            <div class="questions-wrap mt-10px">
              <div v-for="(i, index) in questions" :key="i.questionId" class="item">
                <div v-for="(q, q_index) in i.stem.sqs" :key="q_index">
                  <Stem :data="q" />
                  <div class="hr my-30px" v-show="q_index < i.stem.sqs.length - 1"></div>
                </div>
                <div class="hr my-30px" v-show="index < questions.length - 1"></div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </template>
  </Page>
</template>

<script>
import Page from '@/components/page'
import Stem from '@/components/question/stem'
import { mapState } from 'vuex'
import { formatQuestionStem } from '@/utils/question'
import Mixin from '../mixin'
import { getEnglishPracticeApi, getNextEnglishQuestionApi } from '@/api/exercise'

export default {
  components: {
    Page,
    Stem
  },
  mixins: [Mixin],
  inject: ['_addTagClickHandler', '_removeTagClickHandler'],
  data() {
    return {}
  },
  computed: {
    ...mapState(['exerciseCenter']),
    questions() {
      const { questions } = this.exerciseCenter.currentPractice

      return questions
        .map((_q, _index) => {
          const { questionDto } = _q

          if (!questionDto) return null

          const {
            stem: { structure_type }
          } = questionDto

          if (structure_type === 'collector.dialogue') {
            const {
              questionId,
              stem: {
                info: { question }
              },
              answer,
              remoteStudentAnswer = {}
            } = questionDto
            const { studentScore, questionScore, studentAnswer } = remoteStudentAnswer

            let sqs = []
            question.forEach((q, index) => {
              const { ask = '', askaudio = '', analyze = '', std = [] } = q
              let answeraudio = ''

              try {
                const { anSqs } = studentAnswer

                answeraudio = anSqs[index].ans[0].anStudentUrl
              } catch (error) {}

              const templateSpeakerSelf = answeraudio
                ? `<span class="append-speaker"><img src="static/icons/speaker.png" data-question-id="${questionId}" data-audio-src="${answeraudio}" /></span>`
                : '<span class="text-FF4040">（未作答）</span>'
              const templateSpeakerStem = `<span class="append-speaker"><img src="static/icons/speaker.png" data-question-id="${questionId}" data-audio-src="${askaudio}" /></span>`

              let templateScore = `<div><span class="text-FF4040">${
                index + 1
              }.</span>${templateSpeakerSelf}</div>`
              let templateQuestion = `<div><span style="margin-right: 0.12rem;">问题：${ask.replace(
                /ets_th[0-9]\s/,
                `${index + 1}.`
              )}</span>${templateSpeakerStem}</div>`
              let templateAnalyze = `<div class="mt-20px">${analyze.replace(/^<\/br>/, '')}</div>`
              let templateAnswer = `<div class="mt-20px text-30C9A1">参考答案：${std
                .map((s) => `</br>● ${s.value}`)
                .join('')}</div>`

              try {
                const { anSqs } = studentAnswer

                const { studentScore: score = 0, questionScore: totalScore = 0 } =
                  anSqs[index].ans[0]

                templateScore = `<div><span class="text-${this.getScoreClass(
                  score / totalScore
                )}">${
                  index + 1
                }.（得分：${score}分/${totalScore}分）</span>${templateSpeakerSelf}</div>`
              } catch (error) {}

              const html = `<div>${templateScore}${templateQuestion}${templateAnalyze}${templateAnswer}</div>`
              sqs.push({
                html,
                og: null,
                sqs: [],
                type: '复合题'
              })
            })

            return {
              questionId,
              stem: formatQuestionStem({
                html: '<div></div>',
                og: null,
                sqs,
                type: '英语听说-听后回答'
              }),
              answer,
              studentAnswer,
              studentScore,
              questionScore
            }
          } else {
            return null
          }
        })
        .filter((q) => !!q)
    },
    score() {
      let score = 0
      this.questions.forEach((q) => {
        const { studentScore } = q
        score += studentScore
      })

      return score
    },
    totalScore() {
      let totalScore = 0
      this.questions.forEach((q) => {
        const { questionScore } = q
        totalScore += questionScore
      })

      return totalScore
    }
  },
  mounted() {
    this._addTagClickHandler('img', this.handleImgClick)
    console.log(this.questions)
  },
  beforeDestroy() {
    this._removeTagClickHandler('img', this.handleImgClick)
  },
  methods: {
    handleImgClick(node) {
      const { currentSrc = '' } = node
      if (currentSrc.indexOf('speaker.png') != -1) {
        const { audioSrc } = node.dataset

        if (!audioSrc || audioSrc === 'undefined') {
          this.$message.error('未作答')
          return
        }

        this.playAudio(node, audioSrc)
      }
    },
    async goToNextQuestion() {
      const {
        record: { courseId, difficultyLevel, questionTypeId },
        questions
      } = this.exerciseCenter.currentPractice
      const questionId =
        Array.isArray(questions) && questions.length > 0 ? questions[0].questionId : undefined

      // 加载动画
      const loading = this.$loading({
        lock: true,
        text: '加载中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.5)'
      })
      // 一分钟内加载不成功关闭loading弹窗
      const timer = setTimeout(() => {
        loading.close()
      }, 60000)

      const { data: record } = await getEnglishPracticeApi({
        courseId,
        difficultyLevel,
        questionTypeId
      })
      const { data: question, msg } = await getNextEnglishQuestionApi({
        questionId,
        courseId,
        difficultyLevel,
        questionTypeId,
        kpointPracticeId: record.id
      })

      // 关闭加载动画
      clearTimeout(timer)
      loading.close()

      if (!question) {
        this.$message.error(msg)
      } else {
        this.$store.commit('setCurrentPractice', {
          record: Object.assign(record, { kpointIds: [record.kpointId] }),
          questions: [question],
          questionIndex: 0
        })

        this.$router.replace('/pages/exercise/practice/english/index').then(() => {
          this.$store.commit('setCurrentPractice', {
            record: Object.assign(record, { kpointIds: [record.kpointId] }),
            questions: [question],
            questionIndex: 0
          })
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.nav-bar-btns {
  .item {
    height: 30px;
    .icon {
      width: 22px;
      height: 22px;
    }

    .name {
      font-size: 22px;
      line-height: 22px;
    }
  }
}

.container {
  border-radius: 16px;

  .overview {
    font-size: 20px;
  }

  .questions-wrap {
    .item {
      /deep/ .append-speaker {
        display: inline-block;
        width: 46px;
        height: 46px;
        position: relative;

        img {
          width: 46px;
          height: 46px;
          position: absolute;
          top: 50%;
          transform: translateY(-24%);
        }

        .playing {
          @keyframes play {
            0% {
              opacity: 0.5;
            }

            25% {
              opacity: 0.25;
            }

            50% {
              opacity: 0.5;
            }

            75% {
              opacity: 0.75;
            }

            100% {
              opacity: 1;
            }
          }

          animation: play 1s ease-in-out infinite backwards;
        }
      }

      .hr {
        height: 1px;
        background: #eee;
      }
    }
  }
}
</style>
